<template>
	<div class="container">
		<div style="position:absolute; right: 20px;">
			<a-button style="margin-left: 10px;" @click="printElement('auxiliary-info-page')">打印/导出PDF</a-button>
			<a-button style="margin-left: 10px;" @click="closeTab('/auxiliary')">
				<close-outlined />关闭
			</a-button>
		</div>
		<div id="auxiliary-info-page">
			<a-form ref="formRef" :model="formState">
				<a-descriptions title="辅助物资申请计划" bordered size="middle">
					<a-descriptions-item label="项目名称" :span="2">{{ formState.project?.name }}</a-descriptions-item>
					<a-descriptions-item label="预约申请单号">{{ formState.code }}</a-descriptions-item>
					<a-descriptions-item label="接收联系人">{{ formState.receiver }}</a-descriptions-item>
					<a-descriptions-item label="联系人电话">{{ formState.receiver_tel }}</a-descriptions-item>
					<a-descriptions-item label="送达日期">{{ formState.deliver_time }}</a-descriptions-item>
					<a-descriptions-item label="送达地址">{{ formState.deliver_address }}</a-descriptions-item>
				</a-descriptions>
			</a-form>
		</div>
		<a-form ref="formRef" :model="formState" layout="vertical" @finish="savePurchase">
			<a-row :gutter="20">
				<a-col :span="24">
					<h3 style="margin: 10px 0;">本次采购物资清单</h3>
				</a-col>
				<a-col :span="24">
					<a-table :data-source="formState.materials" :columns="planMaterialColumns" :row-key="(record) => record.key" :pagination="false">
					</a-table>
				</a-col>
				<a-col :span="24">
					<a-form-item label="备注" name="memo">{{ formState.memo }}</a-form-item>
				</a-col>
			</a-row>
			<a-workflow v-if="formState.id" v-model:status="formState.workflow_status" module="auxiliary" :target-id="formState.id" :project-id="formState.project_id" :code="formState.code" :user-id="formState.apply_id" :extra="true" :steps="true" @submit="(e) => console.log(e)"></a-workflow>
			<a-row :gutter="20">
				<a-col :span="24" class="py-4 text-center">
					<a-space>
						<a-button @click="closeTab('/auxiliary')">
							<close-outlined />关闭
						</a-button>
					</a-space>
				</a-col>
			</a-row>
		</a-form>
	</div>
</template>

<script setup>
import { ref, computed, onMounted, getCurrentInstance, inject } from "vue";
import { CloseOutlined } from "@ant-design/icons-vue";
import { post, listToTree } from "../utils";
import { useRoute } from "vue-router";
import { add, subtract } from "@/utils/operation.js";
import { printElement } from "@/utils/exportData.js";
import { AWorkflow } from "@/components/index.js";

const route = useRoute();
const id = computed(() => {
	return route.params.id || 0;
});
const formState = ref({ materials: [] });
const contractlist = ref([]); //	合同列表
const userlist = ref([]); // 供应商列表
const formRef = ref();
const { proxy } = getCurrentInstance();
const addMaterialModel = () => {
	formState.value.materials.push({ key: formState.value.materials.length });
};

const planMaterialColumns = [
	{
		title: "ID",
		dataIndex: "id",
		width: 60,
		align: "center"
	},
	{
		title: "物资名称",
		dataIndex: "name",
		width: 200,
		ellipsis: true
	},
	{
		title: "型号规格",
		dataIndex: "model",
		width: 150,
		ellipsis: true
	},
	{
		title: "单位",
		dataIndex: "unit",
		width: 130,
		align: "center"
	},
	{
		title: "数量",
		dataIndex: "quantity",
		width: 100,
		align: "center"
	},
	{
		title: "备注",
		dataIndex: "memo",
		width: 200,
		align: "center"
	},
];

//projectOptions
const projectOptions = ref([]);
post("department/projects?type=3").then(({ data }) => {
	projectOptions.value = data.map(d => {
		return {
			value: d.id,
			label: d.name,
			leader: d.leader,
			phone: d.phone,
			address: d.address
		};
	});
});

post("dictionary", { root_id: 56 }).then(data => {
	const { root_id: rootId } = data[0] || {};
	materialOptions.value = listToTree(data, rootId);
});

const materialOptions = ref([]);
const modelOptions = ref({});
const unitOptions = ref({});
const changeProject = project_id => {
	return new Promise((resolve, reject) => {
		formState.value.receiver_id = null;
		post("project/user", { project_id, scene: "main", status: "1" }).then(data => {
			userlist.value = data.map(d => ({
				label: d.fullname || d.username,
				value: d.id,
				mobile: d.mobile
			}));
		});
		post("contract/all", { project_id: project_id, types: "4" }).then(data => {
			modelOptions.value = {};
			unitOptions.value = {};

			if (!data.length) {
				contractlist.value = [];
				formState.value.project_id = null;
				proxy.$message.error("当前项目尚未绑定合同");
				return resolve();
			}

			contractlist.value = data;
			//自动完善地址信息
			const projectInfo = projectOptions.value.find(d => d.value === project_id);
			formState.value.deliver_address = projectInfo?.address;

			resolve();
		});
	});
};
const changeUser = (userId) => {
	const user = userlist.value.find(d => d.value === userId);
	formState.value.receiver = user.label;
	formState.value.receiver_tel = user.mobile;
}
//检验数量
onMounted(() => {
	const cacheData = localStorage.getItem("auxiliary-save");
	formState.value = JSON.parse(cacheData) || formState.value;

	if (id.value) {
		post("auxiliary/info", { id: id.value }).then(async data => {
			await changeProject(data.project.id);
			data.materials = data.materials.map(item => {
				const { quantity, unit, memo } = item.AuxiliaryMaterial;
				return {
					...item,
					quantity,
					unit,
					memo,
				};
			});
			formState.value = data;
		});
	}
});

const savePurchase = () => {
	formRef.value
		.validate()
		.then(() => {
			proxy.$message.destroy();
			const params = { ...formState.value };

			if (!contractlist.value.length) {
				proxy.$message.error("当前项目尚未绑定合同");
				return;
			}

			if (!params.materials.length) {
				proxy.$message.error("请添加材料清单");
				return;
			}

			params.materials = JSON.stringify(
				params.materials.map(({ id, unit, quantity, memo }) => {
					return {
						id,
						unit,
						quantity,
						memo
					};
				})
			);

			params.contract_ids = contractlist.value.map(item => item.id).join(",");
			post("auxiliary/save", params)
				.then(() => {
					if (id.value) {
						proxy.$message.success("辅助申请修改成功", 1);
					} else {
						proxy.$message.success("辅助申请创建成功", 1);
					}

					closeTab("/auxiliary");
					localStorage.removeItem("auxiliary-save");
				})
				.catch(err => {
					proxy.$message.error(err);
				});
		})
		.catch(err => {
			proxy.$message.error(err.message);
		});
};

const submitPurchase = () => {
	proxy.$message.success("采购单提交成功", 1);
	closeTab("/purchase");
};

const materialModelOptions = ref({});

//调用父页面closeTab方法
/*
//父页面定义closeTab方法
provide("closeTab", path => {
	
});
*/
const closeTab = inject("closeTab");
</script>

<style scoped lang="scss">
.container {
	background: #fff;
	padding: 12px;

	h2 {
		font-size: 16px;
		font-weight: 600;
		line-height: 30px;
		margin-bottom: 20px;
	}

	h3 {
		line-height: 40px;
		font-size: 16px;
		font-weight: 400;
		margin-bottom: 20px;

		display: flex;
		align-items: center;

		&:before {
			content: "";
			display: block;
			width: 2px;
			height: 20px;
			background: rgb(24, 144, 255);
			margin-right: 10px;
		}
	}

	h4 {
		font-weight: 600;
		margin: 15px 0;
		line-height: 30px;
	}
}

:deep(.ant-table-cell) .ant-form-item {
	margin-bottom: 0;

	.ant-form-item-explain {
		position: absolute;
		bottom: -24px;
	}
}

.cache-btn {
	background-color: #0d9424;
	color: #fff;
}
</style>
